package com.app.wifi_gps_tethering;


import android.location.Location;
import android.text.format.Time;

public class GeoConvertor {
	public static final String RMC_HEADER_STRING = "$GPRMC";
	public static final String GGA_HEADER_STRING = "$GPGGA";
	enum NMEA_TYPE { RMC, GGA, UNKNOWN };
	
	public Location ConvertFromNMEA(Location location, String nmea){
		
		NMEA_TYPE nmeaType = checkNMEA(nmea); 
		switch(nmeaType)
		{
			case RMC:
				location = fromRMC(location, nmea);
				break;
			case GGA:
				location = fromGGA(location, nmea);
				break;
			case UNKNOWN:
			default:
				break;
		}
		return location;
	}
	
	private NMEA_TYPE checkNMEA(String nmea) {
		NMEA_TYPE nmeaType = NMEA_TYPE.UNKNOWN;
		
		String[] arr_nmea = nmea.split(",");
		if(arr_nmea[0].equals(RMC_HEADER_STRING))
			nmeaType = NMEA_TYPE.RMC;
		if(arr_nmea[0].equals(GGA_HEADER_STRING))
			nmeaType = NMEA_TYPE.GGA;		
		return nmeaType;
	}
	
	private Location fromRMC(Location loc, String rmc) {
		String[] arr_str = rmc.split(",");
		loc.setTime(getTime(arr_str[1], arr_str[9]));
		loc.setLatitude(getDegree(arr_str[3], arr_str[4]));
		loc.setLongitude(getDegree(arr_str[5], arr_str[6]));
		loc.setBearing(Float.parseFloat(arr_str[8]));
		//loc.setAccuracy(accuracy);
		loc.setSpeed(getSpeed(arr_str[7]));
		return loc;
	}
	
	private Location fromGGA(Location loc, String gga) {
		String[] arr_str = gga.split(",");
		loc.setLatitude(getDegree(arr_str[2], arr_str[9]));
		loc.setLongitude(getDegree(arr_str[4], arr_str[5]));
		loc.setAltitude(getAlt(arr_str[8], arr_str[9]));
		return loc;
	}
	
	private long getTime(String strTime, String strDate) {
		Time time = new Time();
		
		time.monthDay = Integer.parseInt(strDate.substring(0, 2));
		time.month = Integer.parseInt(strDate.substring(2, 4));
		time.year = Integer.parseInt(strDate.substring(4, 6)) + 2000;
		
		time.hour = Integer.parseInt(strTime.substring(0, 2));
		time.minute = Integer.parseInt(strTime.substring(2, 4));
		time.second = Integer.parseInt(strTime.substring(4, 6));
		
		return time.toMillis(false);
	}
	
	private double getDegree(String str, String strSign) {
		int minOffset = (strSign.equals("E") || strSign.equals("W") ? 3: 2);
		double sign = (strSign.equals("S") || strSign.equals("W") ? -1: 1);
		double degree = Double.parseDouble(str.substring(0, minOffset));
		degree += Double.parseDouble(str.substring(minOffset, str.length())) / 60;
		return degree * sign;
	}
	
	private float getSpeed(String str)
	{
		float speed = Float.parseFloat(str);
		return speed / 1.9438f; 
	}
	
	private double getAlt(String str, String strUnit)
	{
		double alt = Double.parseDouble(str);
		if(!strUnit.equals("M"))
			alt *= 0.3048;
		return alt; 
	}	
	
	
}
